﻿using etracks.Helpers;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace etracks.Web.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Login ()
        {
            ViewBag.Title = "login | etracks";
            return View (new LoginViewModel());
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            Session.Abandon();
            return RedirectToAction("Index", "Home");
        }

        [HttpPost]
        public ActionResult Login(LoginViewModel vm)
        {
            bool validCredentials = IsCredentialsValid(vm.Username, vm.Password);

            try 
            {
                if (validCredentials) // If credentials are valid
                {
                    // FormsAuthentication.SlidingExpiration
                    FormsAuthentication.SetAuthCookie("zhixian", true);

                    if (String.IsNullOrEmpty(Request.QueryString["ReturnUrl"]))
                    {
                        return RedirectToAction("Index", "Home");
                    }
                    else
                    {
                        return new RedirectResult(Request.QueryString["ReturnUrl"]);
                    }
                }
                else
                {
                    vm.Message = "Invalid credentials.";
                }
            } catch {

                return View ();
            }

            return View(vm);
        }

        ////////////////////////////////////////////////////////////////////////////////
        // Data retrieval hack functions
        private static bool IsCredentialsValid(string username, string password)
        {
            bool result = false;
            Dictionary<string, object> parameters = new Dictionary<string, object>();

            parameters.Add("username", username);

            DataTable dt = PostgresHelper.GetDataTable(@"SELECT id, username, password_hash, password_salt, password_timestamp FROM public.account WHERE username = :username;", 
                parameters);

            if ((dt != null) && (dt.Rows.Count > 0))
            {
                DataRow r = dt.Rows[0];

                string base64Hash = CryptographyHelper.Hash(string.Format("{0}{1}", r["password_salt"].ToString(), password));

                if (base64Hash == r["password_hash"].ToString())
                {
                    result = true;
                }
            }

            return result;
        }

        public static void SetPassword(string username)
        {
            string newSalt = CryptographyHelper.GetPrintablePassword(8);
            string newPassword = CryptographyHelper.GetPrintablePassword(8);
            newPassword = "p@ssw0rd";
            string base64Hash = CryptographyHelper.Hash(string.Format("{0}{1}", newSalt, newPassword));

            Dictionary<string, object> parameters = new Dictionary<string, object>();

            parameters.Add("id", username);
            parameters.Add("password_hash", base64Hash);
            parameters.Add("password_salt", newSalt);

            int rowsAffected = PostgresHelper.Execute(@"UPDATE  public.account
SET     password_hash = :password_hash,
        password_salt = :password_salt,
        password_date = now()
WHERE   id = :id;", parameters);

        }
    }
}